/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.notice.lark.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.dtflys.forest.Forest;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.notice.facade.NoticeServiceFacade;
import info.peigen.hotpot.component.notice.facade.order.SimpleNoticeOrder;
import info.peigen.hotpot.component.notice.facade.order.TemplateNoticeOrder;
import info.peigen.hotpot.component.notice.facade.result.NoticeResult;
import info.peigen.hotpot.component.notice.lark.config.NoticeLarkProperties;
import info.peigen.hotpot.component.notice.lark.request.NoticeLarkWebHookRequest;
import info.peigen.hotpot.component.notice.lark.request.NoticeLarkWebHookRequestContent;
import info.peigen.hotpot.component.notice.lark.response.NoticeLarkWebHookResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * <b>(LarkNoticeService)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/10/19
 */
@Slf4j
@Component
public class NoticeLarkService implements NoticeServiceFacade {
    @Inject
    private NoticeLarkProperties noticeLarkProperties;

    @Override
    public NoticeResult sendSimpleNotice(SimpleNoticeOrder order) {
        NoticeLarkWebHookRequest request = NoticeLarkWebHookRequest.builder()
                .content(NoticeLarkWebHookRequestContent.builder().text(order.getReceiver()).build())
                .build();
        // request.setSign(genSign(request.getTimestamp()));
        String str = Forest.post(noticeLarkProperties.getNoticeUrl())
                .contentTypeJson()
                .charset("utf-8")
                .addBody(JSON.toJSONString(request))
                .executeAsString();
        log.info(str);
        NoticeLarkWebHookResponse response = JSON.parseObject(str, NoticeLarkWebHookResponse.class);

        return parse(response);
    }

    @Override
    public NoticeResult sendTemplateNotice(TemplateNoticeOrder order) {
        return null;
    }

    private NoticeResult parse(NoticeLarkWebHookResponse response) {
        Assert.notNull(response, () -> new BusinessException(ResultCode.FAILURE, "NoticeLarkWebHookResponse不得为空!"));

        NoticeResult result = new NoticeResult();
        if (StrUtil.isAllNotEmpty(response.getStatusCode(), response.getStatusMessage())) {
            result.setSuccess();
        } else {
            result.setFail(response.getMsg());
        }
        return result;
    }

    private String genSign(long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        // 把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + noticeLarkProperties.getSecret();
        // 使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }
}